import React, { useEffect, useMemo, useState } from "react"
import { View, Input, Button, Picker, Text } from "@tarojs/components"
import { AtModal, AtModalContent, AtModalAction, AtModalHeader } from "taro-ui"
import { accountType, fixedIncomeType } from "@/types";
import { billTypeMap, billTypes, cycleList, cycleMap, enableStatus, enableStatusMap } from "@/dict";
import categorys from "@/store/categorys";
import user from "@/store/user";
import moment from "moment";

import './index.scss'

const fixedIncomeModal: React.FC<{
    fixedData?: fixedIncomeType,
    account?: accountType,
    visible: boolean,
    onCancel: () => void
    onSure: (fixedIncome: fixedIncomeType) => void
}> = React.memo(({ fixedData, account, visible, onCancel, onSure }) => {

    const [fixedIncome, setFixedIncome] = useState<fixedIncomeType>({
        accountId: account?.id,
        amount: 0,
        cycle: 1,
        name: '',
        type: 0,
        userId: user.info?.id,
        userName: user.info?.userName,
        status: 1,
        bookDate: moment().date() > 28 ? 28 : moment().date(),
        category: 1,
    })

    useEffect(() => {
        if (fixedData) {
            setFixedIncome({ ...fixedData })
        }
    }, [fixedData])

    const onInputChange = (value, key) => {
        if (key === 'cycle') {
            fixedIncome.bookDate = 1
        }
        if (key === 'userId') {
            const member = (account?.members) && account.members[value]
            fixedIncome.userName = member?.userName || ''
            setFixedIncome({
                ...fixedIncome,
                userName: member?.userName,
                userId: member?.userId
            })
        } if (key === 'amount') {
            setFixedIncome({
                ...fixedIncome,
                [key]: isNaN(value) ? '' : value
            })
        } else {
            setFixedIncome({
                ...fixedIncome,
                [key]: value
            })
        }
    }

    const bookDates = useMemo(() => {
        const array: { id: number, name: string }[] = []
        if (fixedIncome.cycle === 1) {
            while (array.length < 28) {
                const val = array.length + 1
                array.push({
                    id: val,
                    name: `${val}号`
                })
            }
        } else {
            while (array.length < 7) {
                const val = array.length
                array.push({
                    id: val + 1,
                    name: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'][val]
                })
            }
        }
        return array
    }, [fixedIncome.cycle])

    const bookDatesMap = useMemo(() => {
        return bookDates.reduce((obj, item) => {
            return {
                ...obj,
                [item.id]: item.name,
            }
        }, {})
    }, [bookDates])

    const getUserSlelectedIndex = useMemo(() => {
        return (account?.members || []).findIndex(item => {
            return fixedIncome.userId === item.userId
        })
    }, [fixedIncome.userId])
    const getcategorySlelectedIndex = useMemo(() => {
        return (categorys.categoryList || []).findIndex(item => {
            return fixedIncome.category === item.id
        })
    }, [fixedIncome.category])

    return <AtModal isOpened={visible} closeOnClickOverlay={false}>
        <AtModalHeader>
            <View className="modal-title">固定收支</View>
        </AtModalHeader>
        <AtModalContent>
            <View className="bill-form-container font-size24">
                <View className="form-item-container flex1">
                    <View className="form-item-label first-item flex-row flex-item">
                        <View>名称</View>
                        <View className="flex1"></View>
                    </View>
                    {
                        visible ? <Input className="form-input"
                            placeholder-class="placeholder-style"
                            value={fixedIncome.name}
                            onInput={(e) => onInputChange(e.detail.value, 'name')}>
                        </Input> : null
                    }

                </View>
                <View className="form-item-container">
                    <View className="form-item-label">启用状态</View>
                    <Picker mode='selector' value={fixedIncome.status} onChange={(e) => onInputChange(e.detail.value, 'status')} rangeKey="name" range={enableStatus}>
                        <View className="flex-row flex-item">
                            <View className="form-input">{fixedIncome.status !== undefined ? enableStatusMap[fixedIncome.status] : ''}</View>
                            <View className="flex1"></View>
                            <Text className="iconfont icon-base-right"></Text>
                        </View>
                    </Picker>
                </View>
                <View className="form-item-container">
                    <View className="form-item-label">归属成员</View>
                    <Picker mode='selector' value={getUserSlelectedIndex} onChange={(e) => onInputChange(e.detail.value, 'userId')} rangeKey="userName" range={account?.members || []}>
                        <View className="flex-row flex-item">
                            {fixedIncome.userName ?
                                <View className='form-input'>
                                    {fixedIncome.userName}
                                </View> :
                                <View className="form-input form-no-data">请选择</View>}
                            <View className="flex1"></View>
                            <Text className="iconfont icon-base-right"></Text>
                        </View>
                    </Picker>
                </View>
                <View className="form-item-container">
                    <View className="form-item-label">收支金额</View>
                    {
                        visible ? <Input className="form-input"
                            placeholder-class="placeholder-style"
                            placeholder="请输入"
                            value={fixedIncome.amount ?  `${fixedIncome.amount}` : ''}
                            onBlur={(e) => onInputChange(e.detail.value, 'amount')}
                            type="digit" >
                        </Input> : null
                    }

                </View>
                <View className="form-item-container">
                    <View className="form-item-label">记账分类</View>
                    <Picker value={getcategorySlelectedIndex} onChange={(e) => onInputChange(e.detail.value, 'category')} rangeKey="name" range={categorys.categoryList || []}>
                        <View className="flex-row flex-item">
                            {fixedIncome.category && categorys.categoryMap ?
                                <View className="form-input">
                                    {categorys.categoryMap[fixedIncome?.category].name}
                                </View> :
                                <View className="form-input form-no-data">请选择</View>}
                            <View className="flex1"></View>
                            <Text className="iconfont icon-base-right"></Text>
                        </View>
                    </Picker>
                </View>
                <View className="form-item-container">
                    <View className="form-item-label">收支类型</View>
                    <Picker mode='selector' value={fixedIncome.type} onChange={(e) => onInputChange(e.detail.value, 'type')} rangeKey="name" range={billTypes}>
                        <View className="flex-row flex-item">
                            {fixedIncome.type !== undefined ?
                                <View className="form-input">{billTypeMap[fixedIncome.type]}</View> :
                                <View className="form-input form-no-data">请选择</View>
                            }
                            <View className="flex1"></View>
                            <Text className="iconfont icon-base-right"></Text>
                        </View>
                    </Picker>
                </View>
                <View className="form-item-container">
                    <View className="form-item-label">记账周期</View>
                    <Picker value={fixedIncome.cycle && fixedIncome.cycle - 1} onChange={(e) => onInputChange(Number(e.detail.value) + 1, 'cycle')} rangeKey="name" range={cycleList}>
                        <View className="flex-row flex-item">
                            {fixedIncome?.cycle ?
                                <View className="form-input">
                                    <Text>{cycleMap[fixedIncome.cycle]}</Text>
                                </View> :
                                <View className="form-input form-no-data">请选择</View>}
                            <View className="flex1"></View>
                            <Text className="iconfont icon-base-right"></Text>
                        </View>
                    </Picker>
                </View>
                {fixedIncome.cycle && [1, 2].includes(fixedIncome.cycle) ? <View className="form-item-container">
                    <View className="form-item-label">记账日</View>
                    <Picker value={fixedIncome.bookDate && fixedIncome.bookDate - 1} onChange={(e) => onInputChange(Number(e.detail.value) + 1, 'bookDate')} rangeKey="name" range={bookDates}>
                        <View className="flex-row flex-item">
                            {fixedIncome.bookDate !== undefined ?
                                <View className="form-input">
                                    {bookDatesMap[fixedIncome.bookDate]}
                                </View> :
                                <View className="form-input form-no-data">请选择</View>}
                            <View className="flex1"></View>
                            <Text className="iconfont icon-base-right"></Text>
                        </View>
                    </Picker>
                </View> : null}

            </View>
        </AtModalContent>
        <AtModalAction>
            <Button onClick={onCancel}>取消</Button>
            <Button onClick={() => onSure(fixedIncome)}>确定</Button>
        </AtModalAction>
    </AtModal>
})
export default fixedIncomeModal